<template>
  <el-dialog :close-on-click-modal="false" v-model="visible" title="doris配置" @close="resetForm" width="80%">
    <el-form ref="formRef" :model="formData" :rules="formRules" label-width="120px">
      <el-row>
        <el-col :span="24">
          <el-row>
            <el-col :span="12">
              <el-form-item prop="replicationAllocation" label="副本数">
                <el-input v-model="formData.replicationAllocation" placeholder="请输入副本数" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-col>
        <el-col :span="11">
          <div class="tree">
            <el-tree
              ref="treeRef"
              :data="tableList"
              :props="{ label: 'name' }"
              node-key="value"
              default-expand-all
              :expand-on-click-node="false"
              show-checkbox
              :highlight-current="false"
            ></el-tree>
          </div>
        </el-col>
        <el-col :span="2">
          <el-button type="primary" @click="getSql">
            确定
            <el-icon class="el-icon--right"><Right /></el-icon>
          </el-button>
        </el-col>
        <el-col :span="11">
          <div v-loading="codeLoading">
            <codemirror
              v-model="code"
              placeholder="Coding..."
              :style="{ height: '400px' }"
              :autofocus="true"
              :tabSize="2"
              :extensions="extensions"
            />
          </div>
        </el-col>
        <el-col :span="12" class="mt-2">
          <el-form-item prop="targetId" label="目标数据库">
            <el-select v-model="formData.targetId" placeholder="请选择目标数据库" filterable clearable>
              <el-option v-for="item in dorisList" :key="item._id" :label="item.datasourceName" :value="item._id" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" :loading="submitBtnLoading" @click="handleCreate">确认</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { watch } from 'vue-demi'
import {
  createsStarrocktsProperties,
  findStarrocktsProperties,
  findTableName,
  batchCreateDorisSql,
  batchCreateDorisTable
} from '@/api/datasourceCenter'
import { Codemirror } from 'vue-codemirror'
import { xml } from '@codemirror/lang-xml'
import { sql } from '@codemirror/lang-sql'
import { oneDark } from '@codemirror/theme-one-dark'
import { EditorView } from '@codemirror/view'
import { Right } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { json } from '@codemirror/lang-json'

const code = ref('')
const extensions = [sql(), oneDark]

const props = defineProps({
  datasource: {
    type: Object,
    default: () => {}
  },
  visible: {
    type: Boolean,
    default: false
  },
  dorisList: {
    type: Array,
    default: () => []
  }
})
const emit = defineEmits(['update:visible', 'create', 'update'])
const formRef = ref()
const submitBtnLoading = ref(false)
const codeLoading = ref(false)
const formData = reactive({
  replicationAllocation: '',
  targetId: ''
})
const formRules = reactive({
  replicationAllocation: [{ required: true, trigger: 'blur', message: '请输入副本数！' }],
  targetId: [{ required: true, trigger: 'blur', message: '目标数据库！' }]
})
const tableList = ref([])
const tableSqls = ref([])
const treeRef = ref(null)
const resetForm = () => {
  formRef.value?.resetFields()
  emit('update:visible')
  tableList.value = []
}
const handleCreate = () => {
  formRef.value?.validate((valid) => {
    if (valid) {
      const params = {
        targetId: formData.targetId,
        sqls: tableSqls.value
      }
      submitBtnLoading.value = true
      batchCreateDorisTable(params)
        .then((res) => {
          ElMessage.success(res.data)
          resetForm()
        })
        .finally(() => {
          submitBtnLoading.value = false
        })
    }
  })
}
watch(
  () => props.visible,
  (val) => {
    if (val) {
      console.log(props.datasource)
      console.log(props.dorisList)
      // findStarrocktsProperties(props.datasource._id).then((res) => {
      //   if (res.data) {
      //     Object.assign(formData, res.data)
      //     handleCreate()
      //   }
      // })
      findTableName(props.datasource).then((res) => {
        tableList.value = [
          {
            name: '表',
            value: 'table',
            children: res.data.map((item) => {
              return {
                name: item,
                value: item
              }
            })
          }
        ]
      })
    } else {
      code.value = ''
    }
  }
)
const getSql = () => {
  const checked = treeRef.value.getCheckedKeys(true)
  if (checked.length === 0) {
    ElMessage.warning('请选择表')
    return
  }
  if (formData.replicationAllocation === '') {
    ElMessage.warning('请输入副本数')
    return
  }
  const params = {
    sourceId: props.datasource._id,
    tables: checked,
    replicationAllocation: formData.replicationAllocation
  }
  codeLoading.value = true
  batchCreateDorisSql(params)
    .then((res) => {
      tableSqls.value = res.data
      code.value = ''
      res.data.forEach((item) => {
        code.value += `-- ${item.table}
${item.sql}

`
      })
    })
    .finally(() => {
      codeLoading.value = false
    })
}
</script>

<style lang="scss" scoped>
.tree {
  height: 400px;
  overflow: auto;
}
</style>
